import { defineStore } from "pinia";
import { computed, ref } from "vue";
import type { CartItem } from "@/types/cart";
import { changeCartAPI, changeSelectedAllAPI, deleteCartAPI, fetchCartListAPI } from "@/api/cartApi";

const useCartStore = defineStore("cartStore", () => {

    /*购物车列表*/
    const cartList = ref<CartItem[]>([]);

    /*是否全部选中*/
    const selectedAll = computed(() => cartList.value.every(item => item.selected));

    /*选中的商品数量*/
    const totalCount = computed(() => cartList.value.filter(item => item.selected).length);

    const total = computed(() => cartList.value.filter(item => item.selected).reduce((previousValue, currentValue) => previousValue += currentValue.count * currentValue.nowPrice, 0))

    /*获取购物车列表的请求函数*/
    const fetchCartList = async (): Promise<void> => {
        const { result }: { result: CartItem[] } = await fetchCartListAPI();
        cartList.value = result;
    };

    /*删除购物车列表的请求函数*/
    const deleteCart = async (data: { ids: string[] }): Promise<void> => {
        await deleteCartAPI(data);
    };

    /*修改购物车商品的请求函数*/
    const changeCart = async (data: { selected?: boolean, count?: number }, id: string): Promise<void> => {
        await changeCartAPI(data, id);
    };

    /*购物车全选和取消全选的请求函数*/
    const changeSelectedAll = async (data: { selected: boolean }): Promise<void> => {
        await changeSelectedAllAPI(data);
    };

    return {
        cartList,
        selectedAll,
        totalCount,
        total,
        fetchCartList,
        deleteCart,
        changeCart,
        changeSelectedAll,
    };
});

export default useCartStore;
